package com.earthea.chatbot.login.service.impl;

import cn.hutool.core.util.IdUtil;
import com.earthea.cache.CacheService;
import com.earthea.common.util.JacksonUtils;
import com.earthea.chatbot.domain.LoginUser;
import com.earthea.chatbot.login.common.constant.Constants;
import com.earthea.chatbot.login.common.util.ServletUtils;
import com.earthea.chatbot.login.service.TokenService;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class TokenServiceImpl implements TokenService {
    /**
     * 令牌自定义标识
     */
    @Value("${app.token.header}")
    private String header;

    /**
     * 令牌秘钥
     */
    @Value("${app.token.secret}")
    private String secret;

    /**
     * 令牌有效期（默认30分钟）
     */
    @Value("${app.token.expireTime}")
    private int expireTime;

    @Autowired
    private CacheService cacheService;

    @Override
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = Constants.LOGIN_TOKENS + uuid;
                return JacksonUtils.fromJson(cacheService.get(userKey), LoginUser.class);
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    @Override
    public void setLoginUser(LoginUser loginUser) {
        if (Objects.nonNull(loginUser)) {
            String token = loginUser.getToken();
            if (StringUtils.isNotEmpty(token)) {
                refreshToken(loginUser);
            }
        }
    }

    @Override
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = Constants.LOGIN_TOKENS + token;
            cacheService.del(userKey);
        }
    }

    @Override
    public String createToken(LoginUser loginUser, Boolean rememberMe) {
        String token = IdUtil.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims, rememberMe);
    }

    @Override
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= (10 * DateUtils.MILLIS_PER_MINUTE)) {
            refreshToken(loginUser);
        }
    }

    @Override
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * DateUtils.MILLIS_PER_MINUTE);
        // 根据uuid将loginUser缓存
        String uuid = loginUser.getToken();
        String userKey = Constants.LOGIN_TOKENS + uuid;
        cacheService.setex(userKey, JacksonUtils.toJson(loginUser), expireTime);
    }

    @Override
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = ServletUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims, Boolean rememberMe) {
        Date now = new Date();
        Date validity = new Date(now.getTime() + (rememberMe ? expireTime * DateUtils.MILLIS_PER_MINUTE : 30 * DateUtils.MILLIS_PER_MINUTE)); // 记住我30天，否则8小时
        return Jwts.builder().setClaims(claims).setIssuedAt(now).setExpiration(validity).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    @Override
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request 请求体
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }
}
